package 寒假刷题;

public class 统计数组中峰和谷的数量 {

    public int countHillValley(int[] nums) {
        int cnt = 0;
        int n = nums.length;
        for (int i = 1; i < n-1; i++) {
            int l = i-1;
            int r = i+1;
            while (l>=0 && nums[l]==nums[i])
                l--;
            while (r<n && nums[r]==nums[i])
                r++;
            if (l>=0 && r<n){
                if (nums[l]<nums[i] && nums[r]<nums[i])
                    cnt++;
                if (nums[l]>nums[i] && nums[r]>nums[i])
                    cnt++;
            }
            //去重
            while (i+1<n && nums[i]==nums[i+1])
                i++;
        }
        return cnt;
    }
}
